package com.fpd.third.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fpd.tools.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fpd.model.bean.Logistics;
import com.fpd.model.bean.ResponseXmlBean;
import com.fpd.model.ro.PostBaseInfo;
import com.fpd.third.service.EMS;
import com.fpd.tools.ConvertUtil;
import com.fpd.tools.DateUtil;
import com.fpd.tools.Tool;
import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @desc 生产环境实现类
 * @author wujiangbo
 * @date 2019年11月28日 下午1:58:25
 */
@Service
@Slf4j
public class EmsProduction implements EMS {

	@Value("${ems.getBillNoUrl}")
	private String getBillNoUrl;

	@Value("${ems.updateUrl}")
	private String updateUrl;

	@Value("${ems.logisticsUrl}")
	private String logisticsUrl;

	@Value("${ems.sysAccount}")
	private String sysAccount;

	@Value("${ems.passWord}")
	private String passWord;

	@Value("${ems.appKey}")
	private String appKey;

	@Value("${ems.businessType}")
	private String businessType;

	@Value("${ems.billNoAmount}")
	private String billNoAmount;

	@Value("${ems.version}")
	private String version;

	@Value("${ems.authenticate}")
	private String authenticate;

	public static void main(String[] args) {
		String billNo = "-1";// 邮件号
		String tpl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<XMLInfo>" +
				"<sysAccount>81100050547171</sysAccount>" +
				"<passWord>e10adc3949ba59abbe56e057f20f883e</passWord>" +
				"<billNoAmount>1</billNoAmount>" +
				"<appKey>T28D4da9F93623e4C</appKey>" +
				"<businessType>1</businessType>" +
				"</XMLInfo>";
		String test = Base64.encode(tpl);
		try {
			test = URLEncoder.encode(test, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String result = HttpUtil.get("http://os.ems.com.cn:8081/zkweb/bigaccount/getBigAccountDataAction.do?method=getBillNumBySys&xml="+test);
//		String result = HttpUtil.post("http://os.ems.com.cn:8081/zkweb/bigaccount/getBigAccountDataAction.do?method=getBillNumBySys&xml="+test);
		String xml_str = Base64.decodeStr(result);// Base64解密
		System.out.println(xml_str);
		//log.info("获取邮件号接口返回值(未转换)：{}", xml_str);
		ResponseXmlBean bean = Tool.convertXmlToJavaBean(xml_str, ResponseXmlBean.class);
	}
	@Override
	public ResponseXmlBean updatePrintDatas(PostBaseInfo post) {
		String custPhone = post.getReceivePhone();
		if (StringUtils.isNotNull(custPhone)){
			String [] arr = custPhone.split(",");
			if (arr.length > 1){
				custPhone = arr[arr.length-1];
			}
		}
		String phone2 = post.getReceivePhone2();
		if (StringUtils.isNotNull(phone2)){
			String [] arr = phone2.split(",");
			phone2 = arr[0];
		}
		String tpl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<XMLInfo>" +
				"<sysAccount>"+sysAccount+"</sysAccount>" +
				"<passWord>"+passWord+"</passWord>" +
				"<appKey>"+appKey+"</appKey>" +
				"<printKind>2</printKind>" +
				"<printDatas>" +
				"<printData>" +
				"<bigAccountDataId>"+post.getDistributionNumber()+"</bigAccountDataId>" +
				"<businessType>"+businessType+"</businessType>" +
				"<billno>"+post.getBillNo()+"</billno>" +
				"<dateType>"+2+"</dateType>" +
				"<procdate>"+DateUtil.parseDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS)+"</procdate>" +
				"<scontactor>"+"方明"+"</scontactor>" +
				"<scustMobile>"+post.getSenderPhone()+"</scustMobile>" +
				"<scustAddr>"+post.getSenderAddress()+"</scustAddr>" +
				"<scustComp>"+post.getSenderCompany()+"</scustComp>" +
				"<tcontactor>"+post.getReceiveName()+"</tcontactor>" +
				"<remark>"+"无法联系时，请按收件地址派件到家里或村委会，有问题联系027－52348388/13329735134签收后备注代收关系"+"</remark>" +
				"<tcustMobile>"+ custPhone +"</tcustMobile>" +
				"<tcustTelplus>"+phone2+"</tcustTelplus>" +
				"<tcustAddr>"+post.getReceiveAddress()+"</tcustAddr>" +
				"<cargoType>"+ "文件"+"</cargoType>" +
				"</printData>" +
				"</printDatas>" +
				"</XMLInfo>";
//		HashMap<String, Object> paramMap = new HashMap<>();
//		paramMap.put("sysAccount", sysAccount);
//		paramMap.put("passWord", passWord);
//		paramMap.put("printKind", "2");// 数据类型(1：预制详情单；2：热敏标签式详情单)
//		paramMap.put("appKey", appKey);
//		paramMap.put("bigAccountDataId", post.getDistributionNumber());// 邮件数据唯一标识(邮件数据的主键、配货单号)
//		paramMap.put("businessType", businessType);// 业务类型（1：标准快递；9：快递包裹）
//		paramMap.put("billno", post.getBillNo());// 邮件号
//		paramMap.put("dateType", "2");// 时间类型（1：收寄时间；2：打印时间）
//		paramMap.put("procdate", DateUtil.parseDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));// 时间(YYYY-MM-DD hh:mi:ss)
//		paramMap.put("scontactor", post.getSenderName());// 寄件人姓名
//		paramMap.put("scustMobile", post.getSenderPhone());// 寄件人电话
//		paramMap.put("scustAddr", post.getSenderAddress());// 寄件人地址
//		paramMap.put("scustComp", post.getSenderCompany());// 寄件人公司
//		paramMap.put("tcontactor", post.getReceiveName());// 收件人姓名
//		paramMap.put("tcustMobile", post.getReceivePhone());// 收件人电话
//		paramMap.put("tcustAddr", post.getReceiveAddress());// 收件人地址
//		paramMap.put("cargoType", "文件");// 内件类型（文件/物品）
		String code = Base64.encode(tpl);
		try {
			code = URLEncoder.encode(code, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		long beginTIme = System.currentTimeMillis();

		String result = HttpUtil.get(updateUrl + code);
		long endTIme = System.currentTimeMillis();
		log.info("调用EMS更新邮件信息接口-----花费时长：{}秒", (endTIme - beginTIme) / 1000);
		String xml_str = Base64.decodeStr(result);// Base64解密
		//log.info("调用EMS更新邮件信息接口返回数据（未转换）：{}", xml_str);
		ResponseXmlBean bean = Tool.convertXmlToJavaBean(xml_str, ResponseXmlBean.class);
		//log.info("调用EMS更新邮件信息接口返回数据：{}", bean.toString());
		return bean;
	}

	@Override
	public List<Logistics> getLogisticsInfo(String billNo) {
		List<Logistics> list = new ArrayList<Logistics>();
		try {
			String url = logisticsUrl + billNo;
			HttpRequest request = HttpUtil.createGet(url);
			// 设置验证信息
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("version", version);
			headers.put("authenticate", authenticate);
			request.addHeaders(headers);
			long beginTIme = System.currentTimeMillis();
			HttpResponse response = request.execute();
			long endTIme = System.currentTimeMillis();
			log.info("根据快递单号查询物流信息---接口花费时长：{}秒", (endTIme - beginTIme) / 1000);
			// 获取状态码
			int status = response.getStatus();
			log.info("根据快递单号查询物流信息，状态码：{}", status);
			if (status == 200) {
				byte[] xmlString = response.bodyBytes();
				// 得到物流信息
				String res = new String(xmlString, "UTF-8");
				//log.info("根据快递单号查询物流信息，物流信息：{}", res);
				// 解析物流信息
				JSONObject result_obj = JSONObject.parseObject(res);
				JSONArray jsonArray = result_obj.getJSONArray("traces");
				Logistics logistics = null;
				// 遍历即可，foreach或for循环
				for (Object value : jsonArray) {
					logistics = JSON.parseObject(value.toString(), Logistics.class);
					logistics.setCodeDesc(ConvertUtil.convertCode(logistics.getCode()));
					logistics.setCode2Desc(ConvertUtil.convertCode2(logistics.getCode2()));
					list.add(logistics);
				}
			}
		} catch (UnsupportedEncodingException e) {
			log.error("根据快递单号查询物流信息接口-------异常：{}", e);
		}
		return list;
	}

	// 测试单号：1169599245530
	@Override
	public String getBillNo() {
		String billNo = "-1";// 邮件号
		try {
			String tpl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<XMLInfo>" +
					"<sysAccount>"+sysAccount+"</sysAccount>" +
					"<passWord>"+passWord+"</passWord>" +
					"<billNoAmount>"+billNoAmount+"</billNoAmount>" +
					"<appKey>"+appKey+"</appKey>" +
					"<businessType>"+businessType+"</businessType>" +
					"</XMLInfo>";
			String code = Base64.encode(tpl);
			try {
				code = URLEncoder.encode(code, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			String result = HttpUtil.get(getBillNoUrl+code);
//			HashMap<String, Object> paramMap = new HashMap<>();
//
//			paramMap.put("sysAccount", sysAccount);
//			paramMap.put("passWord", passWord);
//			paramMap.put("appKey", appKey);
//			paramMap.put("businessType", businessType);
//			paramMap.put("billNoAmount", billNoAmount);
			long beginTIme = System.currentTimeMillis();
//			String result = HttpUtil.post(getBillNoUrl, paramMap);
			long endTIme = System.currentTimeMillis();
			log.info("邮政接口返回消息====="+result);
			String xml_str = Base64.decodeStr(result);// Base64解密
			log.info("邮政接口返回消息====="+xml_str);
			ResponseXmlBean bean = Tool.convertXmlToJavaBean(xml_str, ResponseXmlBean.class);
			if (bean != null) {
				if ("1".equals(bean.getResult())) {
					// 调用成功
					billNo = bean.getAssignIds().getAssignId().getBillno();
				}
			}
		} catch (Exception e) {
			log.error("调用EMS接口获取邮件号-------异常：{}", e);
		}
		return billNo;
	}

}
